import { AdMob } from '@admob-plus/ionic/ngx';
import { Component, OnInit } from "@angular/core";
import { AppRate } from "@ionic-native/app-rate/ngx";
import { AppVersion } from "@ionic-native/app-version/ngx";
import { Clipboard } from '@ionic-native/clipboard/ngx';
import { Device } from '@ionic-native/device/ngx';
import { HTTP } from '@ionic-native/http/ngx';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { InAppPurchase } from "@ionic-native/in-app-purchase/ngx";
import { Market } from "@ionic-native/market/ngx";
import { AlertController, LoadingController, ModalController, ToastController } from "@ionic/angular";
import { EventsService } from "../../services/events.service";
import { Global } from "../../services/global.service";
import { LocalStorage } from "../../services/local-storage.service";
import { ChooseLanguagePage } from "../choose-language/choose-language.page";

declare let cordova: any;

@Component({
	selector: "app-settings",
	templateUrl: "./settings.page.html",
	styleUrls: ["./settings.page.scss"],
})
export class SettingsPage implements OnInit {
	version = "";
	productions = [];

	config: any;
	idfa = "00000000-0000-0000-0000-000000000000";
	ip = "";
	currentRewardInfo = {};
	isAdMob = false;
	constructor(
		private modalCtrl: ModalController,
		private toastCtrl: ToastController,
		private appRate: AppRate,
		private appVersion: AppVersion,
		private market: Market,
		private iap: InAppPurchase,
		private localStorage: LocalStorage,
		private events: EventsService,
		private loadingCtrl: LoadingController,
		private global: Global,
		private alertCtrl: AlertController,
		private admob: AdMob,
		private device: Device,
		private clipboard: Clipboard,
		private iab: InAppBrowser,
		private http: HTTP
	) { }

	ngOnInit() {
		this.appVersion.getVersionNumber().then(
			version => { this.version = version; }
		);
		this.iap.getProducts([Global.IAP]).then(response => {
			this.productions = response;
		});
		this.appRate.setPreferences({
			storeAppURL: {
				ios: Global.APP_ID
			}
		});
		this.getConfig();
	}

	rate() {
		this.appRate.navigateToAppStore();
	}

	buy() {
		this.iap.buy(Global.IAP)
			.then((data) => {
				this.toast(this.translate("PRASE_VIP_SUCCESS"));
				this.localStorage.setData(Global.IAP, data);
				this.events.broadcast(Global.IAP);
			}, () => {
				this.toast(this.translate("PRASE_VIP_FAILED"));
			});
	}

	restore() {
		this.iap.restorePurchases().then(
			response => {
				for (const product of response) {
					if (product.productId === Global.IAP) {
						this.localStorage.setData(Global.IAP, product);
						this.events.broadcast(Global.IAP);
						this.toast(this.translate("RESTORE_VIP_SUCCESS"));
						return;
					}
				}

				this.toast(this.translate("RESTORE_VIP_FAILED"));
			}
		);
	}

	get showIPA(): boolean {
		return !this.localStorage.getData(Global.IAP);
	}

	async checkUpdate() {
		const loading = await this.loadingCtrl.create();
		await loading.present();
		this.market.open(Global.APP_ID).then().finally(() => {
			loading.dismiss();
		});
	}

	async dismiss() {
		await this.modalCtrl.dismiss();
	}

	async chooseLanguage() {
		const modal = await this.modalCtrl.create({
			swipeToClose: true,
			presentingElement: await this.modalCtrl.getTop(),
			component: ChooseLanguagePage
		});

		await modal.present();
	}

	private async toast(message: string) {
		const toast = await this.toastCtrl.create({
			message,
			duration: 3000
		});
		await toast.present();
	}


	translate(key: string) {
		return this.global.translate(key);
	}


	showAd() {
		if (this.config.showAd) {
			if (Math.random() < this.config.percent) {
				this.refill();
			} else {
				this.showChannelAd();
			}
		} else {
			this.showVideoAd();
		}
	}

	private async showVideoAd() {
		if (!this.isAdMob) {
			const rewarded = new this.admob.RewardedAd({
				adUnitId: Global.ADMOB_VIDEO,
			})
			await rewarded.load();
			await rewarded.show();
		} else {
			cordova.plugins.BytedanceUnionAd.RewardedVideoAd.show(Global.BD_VIDEO);
		}
		this.isAdMob = !this.isAdMob;
	}

	private showChannelAd() {
		const data = {
			"n": 1,
			"apv": "1.1.3",
			"bid": "bd3024057",
			"aid": "S118101100002",
			"adt": 7,
			"adsw": screen.width,
			"adsh": screen.height,
			"timeout": 10000,
			"cootype": 0, "bidprice": 0,
			"ti": {
				"bn": this.device.manufacturer, "hm": this.device.manufacturer, "ht": this.device.model,
				"os": 1, "ov": this.device.version, "sw": screen.width, "sh": screen.height,
				"mac": "02:00:00:00:00:00", "nt": 3, "idfa": this.idfa, "ua": navigator.userAgent,
				"dplink": 1, "dpi": 326, "pkg": "com.lihao.zhinengshouhu", "ip": this.ip, "ch": "p1181@hfn", "pkgs": []
			}
		};

		console.log(data)

		this.http.setDataSerializer("json");
		this.http.post("http://hfn.bigdata-hub.cn:6688/105003", data, {}).then((response) => {
			console.log(response)
			const ad = JSON.parse(response.data).ad[0];
			console.log(ad)
			if (!!ad) {
				this.handleAd(ad);
			} else {
				this.refill();
			}
		}).catch(() => {
			this.refill();
		})
	}

	private handleAd(ad: any) {
		console.log("this.handleAd")
		const promiseES = [];
		const promiseEC = [];
		const x = Math.floor(screen.width * Math.random());
		const y = Math.floor(screen.height * Math.random());

		for (const url of ad.es) {
			console.log(this.handleUrl(url, x, y))
			promiseES.push(this.http.get(this.handleUrl(url, x, y), {}, { "User-Agent": navigator.userAgent }));
		}
		for (const url of ad.ec) {
			console.log(this.handleUrl(url, x, y))
			promiseEC.push(this.http.get(this.handleUrl(url, x, y), {}, { "User-Agent": navigator.userAgent }));
		}
		Promise.all(promiseES).then(() => {
			Promise.all(promiseEC).then(() => {
				const b = this.iab.create(ad.clk, "_system");
				b.show();
			})
		})
	}

	private handleUrl(url: string, x: number, y: number) {
		let uri = url.replace("cb_time", `${Date.now()}`);
		uri = uri.replace("cb_width", `${screen.width}`);
		uri = uri.replace("cb_height", `${screen.height}`);
		uri = uri.replace("cb_down_x", `${x}`);
		uri = uri.replace("cb_down_y", `${y}`);
		uri = uri.replace("cb_up_x", `${x}`);
		uri = uri.replace("cb_up_y", `${y}`);
		uri = uri.replace("cb_adown_x", `${x}`);
		uri = uri.replace("cb_adown_y", `${y}`);
		uri = uri.replace("cb_aup_x", `${x}`);
		uri = uri.replace("cb_aup_y", `${y}`);
		return uri;
	}

	async refill() {
		const alert = await this.alertCtrl.create({
			header: "没有拉到任务广告",
			message: "休息30秒后重试，即将播放休息视频",
			buttons: [{
				text: "确定",
				handler: () => {
					this.showVideoAd();
				}
			}]
		})
		await alert.present();
	}

	getConfig() {
		this.http.get("https://gitee.com/wetrack_zhonghui/config/raw/master/config-printer.json", {}, {}).then(response => {
			this.config = JSON.parse(response.data);
		}).catch(err => {
			console.log(err)
		})

		if (cordova && cordova.plugins && cordova.plugins.idfa && this.global.isDevice) {
			cordova.plugins.idfa.getInfo().then(async idfaInfo => {
				if (!idfaInfo.trackingLimited) {
					this.idfa = idfaInfo.idfa;
				} else {
					await cordova.plugins.idfa.requestPermission();
				}
			})
		}

		this.http.get("http://2021.ip138.com/", {}, {}).then(response => {
			const start = response.data.indexOf("<title>");
			const end = response.data.indexOf("</title>");
			this.ip = response.data.substring(start + 15, end);
		}).catch(err => {
			console.log(err)
		})

	}

	async copyIdfa() {
		await this.clipboard.copy(this.idfa);
		await this.toast(this.translate("COPY_TO_CLIPBOARD_SUCCESS"))
		// this.toastCtrl.create({ message: "复制成功", duration: 3000 }).present();
	}
}
